import { userInfo } from '@/stores/userInfo'
import { getCurrentInstance } from 'vue'

function hasPermission(userPermissions, required) {
  if (!required) return true
  if (Array.isArray(required)) {
    return required.some((p) => userPermissions.includes(p))
  }
  return userPermissions.includes(required)
}

export default {
  mounted(el, binding) {
    // 延迟加载pinia
    const instance = getCurrentInstance()
    if (!instance) return
    const pinia = instance.appContext.app._context.provides.pinia
    const userInfos = userInfo()(pinia)
    const { value: required, mode = 'hide' } = binding.value || {}
    const userPermissions = userInfos.getUserInfo.permissions || []
    if (!hasPermission(userPermissions, required)) {
      switch (mode) {
        case 'disable':
          el.disabled = true
          el.classList.add('is-disabled')
          break
        case 'hide':
        default:
          el.style.display = 'none'
      }
    }
  },
}
